﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using System.Windows;
using Microsoft.Phone.Tasks;

namespace GameForKids
{




    public class LoginScreen : GameScreen
    {
        // trang thai popup
        public enum LOGSTATE
        {
            zooming,
            ready,
            fillingName
        }

        // trang thai hieu ung luc dau
        public enum STATEZOOM
        {
            to1,
            nho1,
            to2,
            done
        }
        InputAction _quit_action;
       
        // nen
        Texture2D background;
        // khung popup
        Texture2D popupBackground;
        Button okButton;
        float scale = 0.2f;
        LOGSTATE LogState;
        int alpha =0;
        STATEZOOM statezoom;
        SpriteFont font;
        SpriteFont fontVN;
        // kiem tra da bam nut ok
        Boolean vaogame = false;
        Boolean hienloiten = false;
        Boolean hienLoiNhap = false;
        //am thanh
        SoundEffect sound_button;
        SoundEffect sound_popup;
        bool isplayed = false;

        public LoginScreen()
        {
        }

        string Huongdan;
        string TitleForm;
        string TitleAlert;
        string Xacnhan;
        string LoiTen;
        string LoiNhap;

        Vector2 pos_of_huongdan;
        Vector2 pos_of_loi;
        Vector2 pos_of_loi2;

        public override void Activate(bool instancePreserved)
        {

            _quit_action = new InputAction(new Buttons[] { Buttons.Back }, null, true);
            background = ScreenManager.Game.Content.Load<Texture2D>("Login/Images/login_background");

            font = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/LoadFont");
            fontVN = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/HelpFont");

            sound_button = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/button_click");
            sound_popup = ScreenManager.Game.Content.Load<SoundEffect>("Login/Sounds/login_in");

            if (GameForKids.language == GameForKids.ANH)
            {
                popupBackground = ScreenManager.Game.Content.Load<Texture2D>("Login/Images/popup_login_EN");
                Huongdan = "You can log in by enter a name with length must not exceed 8 characters and does not contain space, special characters!";
                TitleForm = "FILL YOUR NAME";
                TitleAlert = "Rate for game !";
                Xacnhan = "Thank you for using our game. If you feel happy, please consider to rate 5 star and post a review for game !";
                LoiTen = "Username is empty or contains special characters, please try again !";
                LoiNhap = "Please enter user name which only use alpha-numeric\n"
                        + "to avoid crash and manage the account better !";
            }
            else
            {
                popupBackground = ScreenManager.Game.Content.Load<Texture2D>("Login/Images/popup_login_VN");
                Huongdan = "Bạn có thể đăng nhập bằng cách nhập một tên mới hoặc tên đã sử dụng trước đó, độ dài không quá 8 kí tự,viết liền không dấu và không chứa kí tự đặc biệt !";
                TitleForm = "ĐIỀN TÊN CỦA BẠN";
                TitleAlert = "Rate for game !";
                Xacnhan = "Cảm ơn bạn đã dùng thử game của chúng tôi. Nếu thấy hay hãy rate 5 sao và để lại nhận xét nhé !";
                LoiTen = "Tên đăng nhập rỗng hoặc chứa kí tự đặc biệt, vui lòng thử lại !";
                LoiNhap = "Vui lòng nhập tên chỉ bao gồm chữ cái không dấu và số\n"
                         +"để tránh lỗi phát sinh và quản lý tài khoản tốt hơn !";
            }

            pos_of_huongdan = new Vector2(GameForKids.WIDTH,440);
            pos_of_loi = new Vector2((GameForKids.WIDTH-fontVN.MeasureString(LoiTen).X)/2, 20);
            pos_of_loi2 = new Vector2((GameForKids.WIDTH - fontVN.MeasureString(LoiNhap).X) / 2, 60);

            okButton = new Button(ScreenManager.Game.Content.Load<Texture2D>("Login/Images/ok_button"),
                ScreenManager.Game.Content.Load<Texture2D>("Login/Images/ok_button_press"),
                ScreenManager.Game.Content.Load<Texture2D>("Login/Images/ok_button"));
            okButton.Location = new Microsoft.Xna.Framework.Point(popupBackground.Width + 280, popupBackground.Height + 160);
            okButton.Clicked += okButton_Clicked;



            LogState = LOGSTATE.zooming;
            statezoom = STATEZOOM.to1;

            base.Activate(instancePreserved);
        }

        Boolean kiemTraChuoi(string s)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(s, "^[a-zA-Z0-9_]*$") || s == null || s == "")
            {
                return false;
            }
            return true;
        }
        void okButton_Clicked(object sender, EventArgs e)
        {
            if(GameForKids.ISMUSIC)
             sound_button.Play();
            if (!kiemTraChuoi(GameForKids.userName))
                hienloiten = true;
            else
            {
                vaogame = true;
                LogState = LOGSTATE.zooming;
            }
        }

        public override void Unload()
        {
            ScreenManager.Game.Content.Unload();
        }

        public override void HandleInput(Microsoft.Xna.Framework.GameTime gameTime, InputState input)
        {
            PlayerIndex player;
            // thoat den dang nhap thi se thoat hoan toan
            if (_quit_action.Evaluate(input, ControllingPlayer, out player))
            {
                if(GameForKids.ISMUSIC)
                sound_popup.Play();
                if (MessageBox.Show(Xacnhan, TitleAlert, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                }
                else
                ScreenManager.Game.Exit();
            }

             TouchCollection touches = input.TouchState;
             if (touches.Count > 0 && LogState == LOGSTATE.ready && !vaogame)
             {
                 TouchLocation touch = touches[0];
                 {
                     okButton.TouchEvent(touch);

                     if(touch.Position.X > 110+(ScreenManager.Game.GraphicsDevice.Viewport.Width - popupBackground.Width*scale)/2 &&
                         touch.Position.X < 370+(ScreenManager.Game.GraphicsDevice.Viewport.Width - popupBackground.Width*scale)/2 &&
                         touch.Position.Y > 90+(ScreenManager.Game.GraphicsDevice.Viewport.Height - popupBackground.Height*scale)/2 &&
                         touch.Position.Y < 140+(ScreenManager.Game.GraphicsDevice.Viewport.Height - popupBackground.Height*scale)/2)
                     {
                         LogState = LOGSTATE.fillingName;
                         
                         Guide.BeginShowKeyboardInput(PlayerIndex.One,
                             TitleForm,
                             "",
                             GameForKids.userName,
                             addName,
                             null);
                     }
                 }
             }
            base.HandleInput(gameTime, input);
        }

        // gan ten player
        public void addName(IAsyncResult result)
        {
            string playerName = Guide.EndShowKeyboardInput(result);
            if (!kiemTraChuoi(playerName))
            {
                playerName = "";
                hienLoiNhap = true;
            }
            if (playerName != null || playerName!="")
            {
                playerName.Trim();
                GameForKids.userName = playerName;
                if (GameForKids.userName.Length > 8)
                    GameForKids.userName = GameForKids.userName.Substring(0, 8);
            }
            
            LogState = LOGSTATE.ready;
        }

        //hieu ung cua thong bao loi
        private float TimeTick = 1000f;
        private float TimeTick2 = 2000f;
        public override void Update(Microsoft.Xna.Framework.GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            if (TimeTick > 0 && hienloiten)
            {
                TimeTick -= elapsed;
            }
            else if (TimeTick <= 0 && hienloiten)
            {
                hienloiten = false;
                TimeTick = 1000f;
            }

            if (TimeTick2 > 0 && hienLoiNhap)
            {
                TimeTick2 -= elapsed;
            }
            else if (TimeTick2 <= 0 && hienLoiNhap)
            {
                hienLoiNhap = false;
                TimeTick2 = 2000f;
            }
            //cap nhat vi tri huong dan
            pos_of_huongdan.X -= 3;
            if (pos_of_huongdan.X < 0 - fontVN.MeasureString(Huongdan).X)
                pos_of_huongdan.X = GameForKids.WIDTH;


            // hieu ung khi hien popup
            if (alpha < 255 && !vaogame)
            {
                alpha += 20;
                if (alpha > 255)
                    alpha = 255;
                if (alpha > 100 && statezoom == STATEZOOM.to1 && !isplayed && GameForKids.ISMUSIC)
                {
                    sound_popup.Play();
                    isplayed = true;
                }
            }

            // hieu ung khi tat popup
            if (vaogame)
            {
                scale -= 0.1f;
                if (scale <= 0.1f)
                    scale = 0.1f;
                alpha -= 20;
                if (alpha <= 0)
                    alpha = 0;
                if ( alpha < 10)
                {
                    GameForKids.gameState = GameState.MainMenu;
                    ScreenManager.Game.Content.Unload();
                    ExitScreen();
                    ScreenManager.AddScreen(new MainMenuScreen(), null);
                }
            }

            // hieu ung ban dau
            if (statezoom == STATEZOOM.to1)
                scale += 0.1f;

            if (scale >= 1.0f && statezoom == STATEZOOM.to1)
                statezoom = STATEZOOM.nho1;

            if (statezoom == STATEZOOM.nho1)
                scale -= 0.02f;

            if (scale < 0.86f && statezoom == STATEZOOM.nho1)
                statezoom = STATEZOOM.to2;

           if (statezoom == STATEZOOM.to2)
                scale += 0.02f;

            if (scale >= 1.0f && statezoom == STATEZOOM.to2)
            {
                LogState = LOGSTATE.ready;
                statezoom = STATEZOOM.done;
            }
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        {
            SpriteBatch spritebatch = ScreenManager.SpriteBatch;
            spritebatch.Begin();

            spritebatch.Draw(background, new Rectangle(0, 0, background.Width, background.Height), new Color(alpha, alpha, alpha));
      
            spritebatch.Draw(popupBackground,
                new Vector2((ScreenManager.Game.GraphicsDevice.Viewport.Width - popupBackground.Width*scale)/2,
                    (ScreenManager.Game.GraphicsDevice.Viewport.Height - popupBackground.Height*scale)/2),
                null,
                new Color(alpha,alpha,alpha),
                0f,
                Vector2.Zero,
                scale,
                SpriteEffects.None,
                0);

            spritebatch.DrawString(font,
                GameForKids.userName,
                new Vector2((ScreenManager.Game.GraphicsDevice.Viewport.Width - popupBackground.Width * scale) / 2 + 130*scale,
                    (ScreenManager.Game.GraphicsDevice.Viewport.Height - popupBackground.Height * scale) / 2 + 100*scale),
                    new Color(0, 0, 0),
                    0f,
                    Vector2.Zero,
                    scale-0.1f,
                    SpriteEffects.None,
                    0);

           if (LogState == LOGSTATE.ready)
            {
                okButton.Location = new Microsoft.Xna.Framework.Point((int)(GameForKids.WIDTH - popupBackground.Width * scale) / 2 + 280,
                    (int)(ScreenManager.Game.GraphicsDevice.Viewport.Height - popupBackground.Height*scale)/2 + 160);
                okButton.Draw(spritebatch);
            }
            
            //viet huong dan
            spritebatch.DrawString(fontVN, Huongdan, pos_of_huongdan, Color.Black);
            // hien loi dang nhap
            if(hienloiten)
                spritebatch.DrawString(fontVN, LoiTen, pos_of_loi, Color.Red);
            if (hienLoiNhap)
                spritebatch.DrawString(fontVN, LoiNhap, pos_of_loi2, Color.White);
            //xem RAM
           /* var appCurrentMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            var appPeakMemoryUsage = DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
            spritebatch.DrawString(font, "Current RAM: " + appCurrentMemoryUsage.ToString(), new Vector2(10, 10), Color.White);
            spritebatch.DrawString(font, "Total RAM: " + appPeakMemoryUsage.ToString(), new Vector2(10, 50), Color.White);
            */
            spritebatch.End();
            base.Draw(gameTime);
        }
    }
}
